package com.peng.leetcode.tree;

/**
 * DistributeCoins
 *
 * 979. 在二叉树中分配硬币
 *
 * @author: lupeng6
 * @create: 2021/5/7 15:25
 */
public class DistributeCoins {

    public static void main(String[] args) {

    }

    private int ans = 0;

    public int distributeCoins(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root);
        return ans;
    }

    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = dfs(node.left);
        int r = dfs(node.right);
        ans += Math.abs(l) + Math.abs(r);
        return node.val + l + r - 1;
    }

}
